package test;

import java.util.Stack;

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1.next==null && l2.next==null && l1.val==0 && l2.val==0) {
            return new ListNode(0);
        }
        StringBuilder num1 = toString(l1);
        StringBuilder num2 = toString(l2);
        num1 = sum(num1,num2);

        ListNode ret = new ListNode(-1);
        for(int i = 0; i < num1.length(); i++) {
            add(ret,num1.charAt(i)-'0');
        }
        return ret.next;
    }
    public static StringBuilder sum(StringBuilder num1, StringBuilder num2) {
        StringBuilder ret = new StringBuilder();
        int i = 0,j = 0;
        int len1 = num1.length();
        int len2 = num2.length();
        int carry = 0;
        while(i<len1 || j<len2 || carry==1) {
            int x = i<len1?num1.charAt(i)-'0':0;
            int y = j<len2?num2.charAt(j)-'0':0;
            ret.append((x+y+carry)%10);
            carry = (x+y+carry)/10;
            i++;
            j++;
        }
        return ret;
    }
    public StringBuilder toString(ListNode list) {
        StringBuilder num = new StringBuilder();
        ListNode cur = list;
        while(cur!=null) {
            //顺序拼接 个位数--》
            num.append(cur.val);
            cur = cur.next;
        }
        return num;
    }
    //尾插
    public void add(ListNode list,int val) {
        ListNode node = new ListNode(val);
        if(list.next==null) {
            list.next = node;
        } else{
            ListNode cur = list;
            while(cur.next!=null) {
                cur = cur.next;
            }
            cur.next = node;
        }
    }
}
//可以将这几个代码合并为一个代码，如下：
class test{
    /**
     * 直接遍历两个链表的val值，直接相加，相加的值，直接尾插*/
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1.next==null && l2.next==null && l1.val==0 && l2.val==0) {
            return new ListNode(0);
        }
        ListNode head  = new ListNode();
        ListNode last = head;
        int carry = 0;
        while(l1!=null || l2!=null || carry==1) {
            int x = l1==null?0:l1.val;
            int y = l2==null?0:l2.val;
            last.next = new ListNode((x+y+carry)%10);
            last = last.next;
            carry = (x+y+carry)/10;
            if(l1!=null) {
                l1 = l1.next;
            }
            if(l2!=null) {
                l2 = l2.next;
            }
        }
        return head.next;
    }
}